#coding=utf-8
import sys
import time
import subprocess
import ty_log as logging

class TimeoutError(Exception):
    pass

# def command_run(command,timeout=3):
#     logging.debug('command_run:{} in time:{}'.format(command, timeout))
#     proc = subprocess.Popen(command,bufsize=0,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
#     poll_seconds = 0.250
#     deadline = time.time() + timeout
#     while time.time() < deadline and proc.poll() == None:
#         time.sleep(poll_seconds)
#     if proc.poll() == None:
#         proc.terminate()
#
#     stdout,stderr = proc.communicate()
#     return stdout,stderr,proc.returncode

def command_run(cmd, timeout=5):
    """执行命令cmd，返回命令输出的内容。
    如果超时将会抛出TimeoutError异常。
    cmd - 要执行的命令
    timeout - 最长等待时间，单位：秒
    """
    p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
    t_beginning = time.time()
    seconds_passed = 0
    while True:
        if p.poll() is not None:
            break
        seconds_passed = time.time() - t_beginning
        if timeout and seconds_passed > timeout:
            p.terminate()
            raise Exception('command_run:{} timeout:{}'.format(cmd, time))
        time.sleep(0.1)
    return p.stdout.read()

if __name__ == '__main__':
    result = command_run('dhclient eth0', timeout=5)
    result = command_run('route', timeout=30)
    print('command_run:{}'.format(result))